<?php

	if(isset($url[1]) && $url[1]=='voteforme') {
		$nominats = explode(",", $url[2]);
	} else $nominats = array();
	
	//confirm vote
	if(isset($_GET['voteconfirmationcode']) && trim($_GET['voteconfirmationcode'])!="") {
		$db->Query("SELECT * FROM user;");
		$users = $db->getResults();
		foreach($users as $u) {
			if(md5(SALT.$u['email'])==$_GET['voteconfirmationcode']) {
				$db->Query("UPDATE user_vote SET confirmed = '1' WHERE user_id = '".$u['id']."';");
				$db->Query("SELECT nomination_id FROM user_vote WHERE user_id = '".$u['id']."';");
				$user_votes = $db->getResults();
				foreach($user_votes as $uv) $db->Query("UPDATE nomination SET vote_count = (vote_count+1) WHERE id = '".$uv['id']."';");
				$ret = "<span class='success'>Congratulations! You vote has successfully been confirmed. Thank you.</span>";
			}
		}
		if(!$ret) $ret = "<span class='success'>Sorry, but the vote confirmation code you entered is incorrect.</span>";
	}

	//submit new vote
	$clearform = $flash = false;	
	if(isset($_POST['submit'])) {
		$code = $_POST['validate'];
		$post_email = $_POST['email'];
		$votes = array();
		$db->Query("SELECT * FROM category;");
		while($db->getRow()) {
			if(isset($_POST['category_'.$db->access['id']]) && $_POST['category_'.$db->access['id']]!="")
				$votes[$db->access['id']] = $_POST['category_'.$db->access['id']];
		}
		if(count($votes)>0) {
			if ( strtoupper($_POST['validate']) == strtoupper( trim ( @fread ( @fopen ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt", "r"), filesize ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt" ) ) ) ) ) {
				if(valid_email_address($email)) $flash = submit_vote($_POST['email'], $votes);
				else $flash = "<span class='error'>Sorry, but the email address you entered is not valid</span>";
				if(!$flash) {
					$flash = "<span class='success'>Thank you for your vote. A confirmation email has been sent to you.</span>";
					unlink ( FILE_SERVER.INCLUDE_DIR."captcha/".$_POST['id'].".txt" );
					$clearform = true;
				}
			} else $flash = "<span class='error'>Sorry, Invalid Authentication Code, Please retype it in and submit again.</span>";
		} else $flash = "<span class='error'>Sorry, You need to vote for at least one the blogs.</span>";
		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $flash;
			exit;
		}
	} else {
		$string = $code = $flash = "";
		//Create an unique validation string
		$chars = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
		for ( $i = 0; $i < 5; $i++ ) $string .= $chars{rand(0, (strlen($chars)-1))};
		$id = time();
		$post_email = "";
		@fwrite ( @fopen ( FILE_SERVER.INCLUDE_DIR."captcha/".$id.".txt", "w" ), $string );
	}
		
	function submit_vote($email, $votes) {
		$db = new CDatabase();
		$db->Connect();
		//check for previously submitted votess. if so delete those old votess, if not add the new user to the db and continue
		$db->Query("SELECT * FROM user WHERE email = '".$email."';");
		if($db->getRow()) {
			$user_id = $db->access['id'];
			$db->Query("SELECT nomination_id FROM user_vote WHERE user_id = '".$user_id."';");
			if($db->getRow()) {
				//$db->Query("UPDATE nomination SET vote_count = (vote_count-".$db->rowsnumber.") WHERE id = '".$db->access[0]."';");
				$db->Query("DELETE FROM user_vote WHERE user_id = '".$user_id."';");
			}
		} else {
			$db->Query("INSERT INTO user(`email`) VALUES ('".$email."');");
			$user_id = $db->insertID;
		}
		
		foreach($votes as $key=>$value) {
			$db->Query("INSERT INTO user_vote(`user_id`, `nomination_id`, `confirmed`) VALUES ('".$user_id."', '".$value."', '0');");
		}
		
		return send_vote_conf_email($email);
	}
	
	function send_vote_conf_email($email) {
		$db = new CDatabase();
		$db->Connect();
		$confirm_link = HTTP_SERVER.'?voteconfirmationcode='.md5(SALT.$email);
		$votes = "";
		$exclude_list = array();
		$db->Query("SELECT DISTINCT category.name, contestant.url FROM user, category, contestant, nomination, user_vote
								WHERE category.id = nomination.category_id 
								AND contestant.id = nomination.contestant_id
								AND nomination.id = user_vote.nomination_id
								AND user.id = user_vote.user_id 
								AND user.email='".$email."' ORDER BY category.id ASC");
		while($db->getRow()) {
			if(!in_array($db->access[0],$exclude_list)) {
				$exclude_list[] = $db->access[0];
				$votes .= "\n".$db->access[0].": \n"." ".$db->access[1]."\n";
			} else $votes .= " ".$db->access[1]."\n";
		}
		
		include_once(FILE_SERVER.INCLUDE_DIR."nxs_mimemail.inc.php");
		$mimemail = new nxs_mimemail();
		$subject = "Vote Confirmation";
		$txt = "Thank you for your vote in the 2007 South African Blog Awards.\n".
					 "\nYour votes were as follows:\n".$votes.
					 "\nIf this is correct please click on the following link or, if the website link bellow doesn't work, please copy and paste it into you browser address bar and press enter.\n".
					 "\nVote Confirmtion Link: ".$confirm_link.
					 "\n\nPlease be reminded that should you submit another the vote this one will be replaced.";

		$html = "<html><body><p>Thank you for your vote in the 2007 South African Blog Awards.</p>".
						"<p>Your votes were as follows:</p>".nl2br($votes).
						"<p>If this is correct please click on the following link or, if the website link bellow doesn't work, please copy and paste it into you browser address bar and press enter.</p>".
						"<p>Vote Confirmtion Link: ".$confirm_link.
						"</p><p>Please be reminded that should you submit another the vote this one will be replaced.</p>";
		$mimemail->new_mail(MASTER_EMAIL, $email , $subject, $text, $html);
		$mimemail->set_from(MASTER_EMAIL, 'SA Blog Awards');
		if($mimemail->send()) return false;
		else return "<span class='error'>Sorry, Unable to send the confirmation email to you.</span>";
	}	
?>